import 'package:redux/redux.dart';
import '../models/visitor_entity.dart';
import '../data/default_visitor_data.dart';

/// Redux访客状态
class ReduxVisitorState {
  final List<VisitorEntity> visitorCollection;

  const ReduxVisitorState({this.visitorCollection = const []});

  ReduxVisitorState copyWith({List<VisitorEntity>? visitorCollection}) {
    return ReduxVisitorState(
      visitorCollection: visitorCollection ?? this.visitorCollection,
    );
  }
}

/// Redux访客动作
abstract class ReduxVisitorAction {}

class InitializeVisitorDataAction extends ReduxVisitorAction {
  final List<VisitorEntity> visitorList;
  InitializeVisitorDataAction(this.visitorList);
}

class AddVisitorAction extends ReduxVisitorAction {
  final VisitorEntity newVisitor;
  AddVisitorAction(this.newVisitor);
}

class RemoveVisitorAction extends ReduxVisitorAction {
  final String visitorId;
  final String targetUserId;
  RemoveVisitorAction({required this.visitorId, required this.targetUserId});
}

/// Redux访客Reducer
ReduxVisitorState visitorReducer(ReduxVisitorState state, dynamic action) {
  if (action is InitializeVisitorDataAction) {
    return state.copyWith(visitorCollection: action.visitorList);
  }

  if (action is AddVisitorAction) {
    final updatedVisitors = List<VisitorEntity>.from(state.visitorCollection)
      ..add(action.newVisitor);
    return state.copyWith(visitorCollection: updatedVisitors);
  }

  if (action is RemoveVisitorAction) {
    final updatedVisitors =
        state.visitorCollection.where((visitor) {
          return !(visitor.visitorId == action.visitorId &&
              visitor.targetUserId == action.targetUserId);
        }).toList();
    return state.copyWith(visitorCollection: updatedVisitors);
  }

  return state;
}

/// Redux访客服务
class ReduxVisitorManager {
  static final ReduxVisitorManager _instance = ReduxVisitorManager._internal();
  factory ReduxVisitorManager() => _instance;
  ReduxVisitorManager._internal();

  Store<dynamic>? _store;

  void initialize(Store<dynamic> store) {
    _store = store;
  }

  Store<dynamic> get store {
    if (_store == null) throw Exception('Visitor service not initialized');
    return _store!;
  }

  void initializeVisitorData() {
    final visitorData = List<VisitorEntity>.from(
      DefaultVisitorDataCollection.defaultVisitorList,
    );
    store.dispatch(InitializeVisitorDataAction(visitorData));
  }

  List<VisitorEntity> getAllVisitors() =>
      List.from(store.state.visitorState.visitorCollection);

  List<VisitorEntity> getVisitorsForUser(String userId) {
    return store.state.visitorState.visitorCollection
        .where((visitor) => visitor.targetUserId == userId)
        .toList();
  }

  List<VisitorEntity> getVisitorsByUser(String visitorId) {
    return store.state.visitorState.visitorCollection
        .where((visitor) => visitor.visitorId == visitorId)
        .toList();
  }

  int getVisitorCountForUser(String userId) {
    return store.state.visitorState.visitorCollection
        .where((visitor) => visitor.targetUserId == userId)
        .length;
  }

  Future<bool> addVisitor(VisitorEntity newVisitor) async {
    try {
      await Future.delayed(const Duration(milliseconds: 300));
      store.dispatch(AddVisitorAction(newVisitor));
      return true;
    } catch (e) {
      return false;
    }
  }

  Future<bool> removeVisitor(String visitorId, String targetUserId) async {
    try {
      await Future.delayed(const Duration(milliseconds: 300));
      store.dispatch(
        RemoveVisitorAction(visitorId: visitorId, targetUserId: targetUserId),
      );
      return true;
    } catch (e) {
      return false;
    }
  }

  int getTotalVisitorCount() =>
      store.state.visitorState.visitorCollection.length;

  List<VisitorEntity> getVisitorsSortedByTime(String userId) {
    final visitors = getVisitorsForUser(userId);
    visitors.sort((a, b) => b.visitTime.compareTo(a.visitTime));
    return visitors;
  }
}
